<?php

namespace pos\services\user;

use pos\extensions\ApiBaseService;
use common\models\mall\MallCartModel;
use pos\services\active\ActivePromotionService;
use common\models\goods\goods\GoodsModel;
use common\models\user\UserModel;
use common\services\cache\CommonCache;


/**
 * Desc 购物车服务类
 * @author WMX
 */
class CartService extends ApiBaseService
{

    /**
     * 购物车列表
     * @param array $params 请求参数
     * * */
    public static function list($params)
    {
        try {
            $headers = \Yii::$app->getRequest()->getHeaders();
            $device = $headers->get('deviceId');
            if (empty($device)) {
                throw new \Exception('收银机号异常');
            }
            $user = UserModel::findOne(['phone' => $params['phone']]);

            $cart = MallCartModel::getAll(['device' => $device], ['id', 'gid', 'count', 'state as select', 'price', 'spec', 'user_id', 'device']);
            if (empty($cart)) {
                $data = [
                    'list' => [],
                    'count' => 0,
                    'total_amount' => 0,
                    'discount_amount' => 0,
                    'manjian_amount' => 0,
                    'total_discount_amount' => 0,
                    'coupon_amount' => 0,
                    'payment_amount' => 0,
                    'act' => [],
                    'transport_amount' => 0.00,
                    'cart' => [],
                    'user' => []
                ];
                if (!empty($user)) {
                    $data['user'] = $user;
                }
                $data['mkey'] = md5('ORDER_INFO_CACHE_' . $device . '_TIME_' . time());
                CommonCache::setCache($data['mkey'], $data, 10 * 60);
                return self::jsonSuccess($data);
            }
            // 计算购物车活动数据
            $data = ActivePromotionService::calcGoodsAmount($cart);
            if (empty($data)) {
                throw new \Exception('活动信息异常');
            }
            //清楚已下架商品
            if ($data['count'] != count($cart)) {
                self::clear($cart, $data, $device);
            }
            //是否全选1：是，2：否
            $data['select'] = count($cart) != array_sum(array_column($cart, 'select')) ? 2 : 1;

            $data['cart'] = [];
            foreach ($data['list'] as &$val) {
                foreach ($val['goods'] as &$goods_item) {
                    $data['cart'][] = $goods_item;
                }
            }
            if (!empty($user)) {
                $data['user'] = $user;
            }
            $data['mkey'] = md5('ORDER_INFO_CACHE_' . $device . '_TIME_' . time());
            CommonCache::setCache($data['mkey'], $data, 10 * 60);

            return self::jsonSuccess($data);
        } catch (\Exception $exc) {
            return self::jsonSuccess([]);
        }
    }

    /**
     * 加入购物车
     * @param array $params 请求参数
     * * */
    public static function add($params)
    {
        try {
            $headers = \Yii::$app->getRequest()->getHeaders();
            $device = $headers->get('deviceId');
            if (empty($device)) {
                throw new \Exception('收银机号异常');
            }
            if (!is_numeric($params['count'])) {
                throw new \Exception('加购数量异常');
            }
            $goods = GoodsModel::findOne(['id' => $params['gid']]);
            if (empty($goods)) {
                throw new \Exception('商品信息异常');
            }
            $cart = MallCartModel::findOne(['gid' => $params['gid'], 'device' => $device, 'spec' => $params['spec']]);
            if (empty($cart)) {
                $cart = new MallCartModel();
            }
            $data = [
                'device' => $device,
                'gid' => $goods['id'],
                'count' => $cart ? $cart->count + $params['count'] : $params['count'],
                'spec' => $params['spec'],
                'price' => $params['price'],
            ];
            $cart->setAttributes($data, false);
            if (empty($cart->save())) {
                throw new \Exception('加购物车异常');
            }
            return self::jsonSuccess([], '加购成功');
        } catch (\Exception $exc) {
            return self::jsonError($exc->getMessage());
        }
    }

    /**
     * 删除购物车
     * @param array $params 请求参数
     * * */
    public static function delete($params)
    {
        try {
            $headers = \Yii::$app->getRequest()->getHeaders();
            $device = $headers->get('deviceId');
            if (empty($device)) {
                throw new \Exception('收银机号异常');
            }

            if ($params['type'] == 2) {
                $where['id'] = $params['id'];
            } else {
                $where = ['device' => $device];
            }
            MallCartModel::deleteAll($where);
            return self::jsonSuccess([], '删除成功');
        } catch (\Exception $exc) {
            return self::jsonError($exc->getMessage());
        }
       
    }

    /**
     * 购物车数量+/-
     * @param array $params 请求参数
     * * */
    public static function opnum($params)
    {
        try {
            $headers = \Yii::$app->getRequest()->getHeaders();
            $device = $headers->get('deviceId');
            if (empty($device)) {
                throw new \Exception('收银机号异常');
            }

            $cart = MallCartModel::findOne(['id' => $params['id'], 'device' => $device]);
            if (empty($cart)) {
                throw new \Exception('操作购物车信息异常');
            }
            if ($cart['count'] == 1 && $params['type'] == 2) {
                $cart->delete();
                return self::jsonSuccess();
            }
            $cart->count = $cart->count + ($params['type'] == 1 ? 1 : -1);
            $cart->save();
            return self::jsonSuccess();
        } catch (\Exception $exc) {
            return self::jsonError($exc->getMessage());
        }
    }


    /**
     * 清除已失效商品
     * **/
    public static function clear($cart, $data, $device)
    {
        $gids = array_column($cart, 'gid');
        $clear = [];
        foreach ($data['list'] as $item) {
            foreach ($item['goods'] as $goods) {
                if (in_array($goods['id'], $gids)) {
                    $clear[] = $goods['id'];
                }
            }
        }
        if ($clear) {
            MallCartModel::deleteAll(['and', ['not in', 'gid', $clear], ['=', 'device', $device]]);
        }
        return true;
    }
}
